﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Downplay.Gravity.Services;
using Downplay.Mechanics.Services;
using Orchard.ContentManagement;
using Downplay.Gravity;
using Downplay.Gravity.Drivers;
using Downplay.Gravity.Filters;
using Downplay.Gravity.Events;
using Orchard.Environment.Extensions;
using Downplay.Mechanics;

namespace Downplay.Relativity.Drops.Drivers
{
    /// <summary>
    /// Turns each type of socket into a drop zone handler
    /// </summary>
    [OrchardFeature("Downplay.Relativity.Drops")]
    public class SocketDropZoneDriver : DropZoneDriver
    {
        private IMechanicsService _mechanicsService;

        public SocketDropZoneDriver(IMechanicsService mechanicsService)
        {
            _mechanicsService = mechanicsService;
        }

        public override IEnumerable<String> ForShapes()
        {
            // Handle socket shape
            yield return "Socket";
        }

        public string GetServiceName()
        {
            return "Socket";
        }
        
        protected override string Identifier(ShapeDataContext context)
        {
            return context.Shape.ContentItem.Id.ToString() + "," +context.Shape.ConnectorType;
        }

        protected override void OnModifyData(ShapeDataContext context, ShapeDataDecoration dec)
        {
            var dict = dec.Data;
            // ? - maybe nothing needed right now
        }

        protected override void OnDropped(AjaxResult result, Gravity.Models.GravityData data, DropZoneData dropData, DragHandleData handleData)
        {
            var zoneId = dropData.ZoneId;
         // public void Dropped(AjaxResult result, string zoneId, string dropId, string dropLeftId, string dropRightId)
            // Ignoring before and after for now, let's work out the intended target

            // ZoneId corresponds to LHS of Socketship (always?)
            var zoneBits = zoneId.Split(',');
            if (zoneBits.Length != 2) return;
            var relateLeftPartId = zoneBits[0].ParseInt();
            if (!relateLeftPartId.HasValue) return;
            var ConnectorType = zoneBits[1];

            var dropId = handleData.DragId;

            // DropId is RHS of Socketship
            var dropBits = dropId.Split(',');
            if (dropBits.Length != 1) return;
            var relateRightPartId = dropBits[0].ParseInt();
            if (!relateRightPartId.HasValue) return;

            var Connector = _mechanicsService.CreateConnector(relateLeftPartId.Value, relateRightPartId.Value, ConnectorType);

            // Trigger AJAX update for this zone wherever it gets rendered
            result.Updates[zoneId] = new object();
        }
   }
}